package com.cwx.mychat.utils.redis;

import com.cwx.mychat.entity.constant.CodeConstant;
import com.cwx.mychat.entity.constant.SysSettingConstant;
import com.cwx.mychat.entity.dto.TokenUserInfoDto;
import com.cwx.mychat.entity.enums.ExceptionBizCodeEnum;
import com.cwx.mychat.exception.BusinessException;
import com.cwx.mychat.utils.jwt.JwtUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component("redisComponent")
public class RedisComponent {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 返回心跳
     * @param
     * @return
     */
    public String getUserHeartbeat(String userId){
        return (String) redisUtil.get(CodeConstant.REDIS_KEY_WS_USER_HEARTBEAT + userId);
    }


    /**
     * 存入心跳
     * @param userId
     * @param
     * @return
     */
    public void saveUserHeartbeat(String userId){
        try{
            String jwt = JwtUtils.createJWT(userId);
            boolean set = redisUtil.set(CodeConstant.REDIS_KEY_WS_USER_HEARTBEAT + userId, jwt, CodeConstant.HEARTBEAT_EXPIRES_SECOND);
            if(!set){
                throw new RuntimeException(ExceptionBizCodeEnum.REDIS_CACHE_FAILED.getMsg());
            }
        }catch (Exception e){
            log.error("Redis缓存心跳失败", e);
        }
    }

    /**
     * 删除心跳
     * @param
     * @return
     */
    public void removeUserHeartbeat(String userId){
       try{
           Object del = redisUtil.del(CodeConstant.REDIS_KEY_WS_USER_HEARTBEAT + userId);
           if(del instanceof Boolean){
               if(!(Boolean) del){
                    throw new RuntimeException(ExceptionBizCodeEnum.REDIS_DELETE_FAILED.getMsg());
               }
           } else if (del instanceof Long) {
               if((Long) del <= 0){
                   throw new RuntimeException(ExceptionBizCodeEnum.REDIS_DELETE_FAILED.getMsg());
               }
           }
       }catch (Exception e){
           log.error("Redis缓存删除心跳失败", e);
       }
    }

    /**
     * 储存tokenUserInfoDto
     * @param tokenUserInfoDto
     * @return
     */
    public void saveTokenUserInfoDto(TokenUserInfoDto tokenUserInfoDto){
        try{
            boolean set = redisUtil.set(CodeConstant.REDIS_KEY_WS_TOKEN + tokenUserInfoDto.getUserId(), tokenUserInfoDto, CodeConstant.REDIS_KEY_EXPIRES_DAY);
//        boolean set2 = redisUtil.set(CodeConstant.REDIS_KEY_WS_TOKEN_USERID + tokenUserInfoDto.getToken(), tokenUserInfoDto.getToken(), CodeConstant.REDIS_KEY_EXPIRES_DAY);
            if (!set) {
                throw new BusinessException(ExceptionBizCodeEnum.REDIS_CACHE_FAILED);
            }
        }catch (Exception e){
            log.error("tokenUserDto缓存失败...", e);
        }
    }

    /**
     * 获取tokenUserInfoDto
     * @param userId
     * @return
     */
    public TokenUserInfoDto getTokenUserInfoDto(String userId){
        TokenUserInfoDto dto = (TokenUserInfoDto)redisUtil.get(CodeConstant.REDIS_KEY_WS_TOKEN + userId);
        return dto;
    }

    /**
     * 删除tokenUserDto
     * @param userId
     */
    public void removeTokenUserInfoDto(String userId){
        try{
            Object del = redisUtil.del(CodeConstant.REDIS_KEY_WS_TOKEN + userId);
            if(del instanceof Boolean){
                if(!(Boolean) del){
                    throw new RuntimeException(ExceptionBizCodeEnum.REDIS_DELETE_FAILED.getMsg());
                }
            } else if (del instanceof Long) {
                if((Long) del <= 0){
                    throw new RuntimeException(ExceptionBizCodeEnum.REDIS_DELETE_FAILED.getMsg());
                }
            }
        }catch (Exception e){
            log.error("tokenUserDto缓存删除失败", e);
        }
    }

    /**
     * 获取系统配置
     * @return
     */
    public SysSettingConstant getSysSetting(){
        SysSettingConstant sysSettingConstant = (SysSettingConstant) redisUtil.get(CodeConstant.REDIS_KEY_SYS_SETTING);
        if(sysSettingConstant == null){
            sysSettingConstant = new SysSettingConstant();
            //重新存入配置
            redisUtil.set(CodeConstant.REDIS_KEY_SYS_SETTING, sysSettingConstant);

        }
        return sysSettingConstant;
    }

    /**
     * 批量添加联系人 失效时间：CodeConstant.REDIS_KEY_EXPIRES_DAY
     * @param userId
     * @param contactIdList
     */
    public void saveUserContactBatch(String userId, List<String> contactIdList){
        try{
            boolean b = redisUtil.lSet(CodeConstant.REDIS_KEY_USER_CONTACT + userId, contactIdList, CodeConstant.REDIS_KEY_EXPIRES_DAY);
            if(!b){
                throw new RuntimeException(ExceptionBizCodeEnum.REDIS_CACHE_FAILED.getMsg());
            }
        }catch (Exception e){
            log.error("联系人缓存失败", e);
        }
    }

    /**
     * 清除所有联系人
     * @param userId
     */
    public void removeUserContactBatch(String userId){
        Object del = redisUtil.del(CodeConstant.REDIS_KEY_USER_CONTACT + userId);
        try{
            if(!(Boolean) del){
                throw new RuntimeException(ExceptionBizCodeEnum.REDIS_DELETE_FAILED.getMsg());
            }
        }catch (Exception e){
            log.error("Redis缓存清除所有联系人失败", e);
        }
    }

    /**
     * 获取所有联系人
     * @param userId
     */
    public List<String> getUserContactBatch(String userId){
        List<Object> userIds = redisUtil.lGet(CodeConstant.REDIS_KEY_USER_CONTACT + userId, 0, -1);
        List<String> collect = (userIds != null) ?
                userIds.stream()
                        .filter(item -> item instanceof String) // 过滤出 String 类型
                        .map(item -> (String) item)
                        .collect(Collectors.toList())
                : new ArrayList<>(); // 返回空列表
        return collect;
    }


}
